#!/usr/bin/env python
#coding:utf-8
#__author__="ybh"
import sys,os
import requests
import json
import time
from aliyunsdkcore.client import AcsClient
from aliyunsdkdomain.request.v20180129 import QueryDomainListRequest
basedir = '/'.join(__file__.split("/")[:-2])
sys.path.append(basedir)
os.environ['DJANGO_SETTING_MODULE']='CrazyEye.settings'
from CrazyEye import settings
import django
django.setup()
from web import models

API="https://oapi.dingtalk.com/robot/send?access_token=07133fed0a8d1c70c34c279653967514ced6f3b3de194b5824250218f9034cef"
zone_list=['cn-qingdao','cn-beijing','cn-zhangjiakou','cn-huhehaote','cn-hangzhou','cn-shanghai','cn-shenzhen']

def main():
    account_list=models.Account.objects.filter(access_id__isnull=False,product='aliyun').exclude(access_id__exact='')
    for account in account_list:
        get_domaininfo(account.username,account.access_id,account.access_secret)


def get_domaininfo(user,access_id,access_secret):
    client = AcsClient(access_id,access_secret)
    request = QueryDomainListRequest.QueryDomainListRequest()
    request.set_PageSize(10)
    request.set_PageNum(1)
    response = client.do_action_with_exception(request).decode('utf-8')
    response=json.loads(response)
    if len(response['Data']['Domain']):
        domain_list=response['Data']['Domain']
        for domain in domain_list:
            expire_time=int(domain['ExpirationDateLong'])/1000
            expire_time_str=time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime(expire_time))
            free_time_s=expire_time-int(time.time())
            domain_name=domain['DomainName']
            text = get_text(user, domain_name, free_time_s, expire_time_str)
            if text != "":
                sendToDingtalk(text)

def get_text(account,domain,free_time,expire_time):
    text=""
    if free_time <  60*60*24*40 and free_time >= 60*60*24*39:
        text += "## 域名\n\n>%s \n\n" % domain
        text += "## 所在阿里云账号\n\n>%s \n\n " % account
        text += "## 到期时间\n\n>%s \n\n" % expire_time
    elif free_time < 60*60*24*30 and free_time >= 60*60*24*29:
        text += "## 域名\n\n>%s \n\n" % domain
        text += "## 所在阿里云账号\n\n>%s \n\n " % account
        text += "## 到期时间\n\n>%s \n\n" % expire_time
    elif free_time < 60*60*24*15 and free_time >= 0:
        text += "## 域名\n\n>%s \n\n" % domain
        text += "## 所在阿里云账号\n\n>%s \n\n " % account
        text += "## 到期时间\n\n>%s \n\n" % expire_time
    return text


def sendToDingtalk(text):
    headers = {'content-type': 'application/json'}
    parames = {
        "msgtype": "markdown",
        "markdown": {
            "title": "域名到期提醒",
            "text": text
        },
    }
    parames = json.dumps(parames)
    r = requests.post(API, data=parames, headers=headers)
    return r.text



if __name__=='__main__':
    main()
